package com.joven.shelltest.test;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * 随机时间
 * @Author wzj
 * @Date 2023-11-03 16:22
 **/
public class OtherTest12 {
    public static void main(String[] args) {
        for (int i = 0; i <= 6; i++) {
//            randomTime();
//            System.out.println(getRandom("2023-11-03"));

            System.out.println(i + ":" + LocalDateTime.now());
            scheduleRandomTask(i);
        }
    }

    private static String randomTime() {
        // 创建一个Calendar实例
        Calendar calendar = Calendar.getInstance();
        // 获取当前时间的小时数
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime start = now.withHour(hour - 6).withMinute(0).withSecond(0);
        LocalDateTime end = now.withHour(hour - 1).withMinute(0).withSecond(0);
        long rand = ThreadLocalRandom.current().nextLong(start.toEpochSecond(ZoneOffset.UTC), end.toEpochSecond(ZoneOffset.UTC));
        LocalDateTime randomTime = LocalDateTime.ofEpochSecond(rand, 0, ZoneOffset.UTC);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        System.out.println(randomTime.format(formatter));
        return randomTime.format(formatter);
    }

    public static String getRandom(String date2) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = dateFormat.parse(date2);
            long time = date.getTime();
            Random random = new Random();
            int i = random.nextInt(24 * 60 * 60 * 1000);
            time = time + i;
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Timestamp timestamp = new Timestamp(time);
            return sdf1.format(timestamp);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static final Random RANDOM = new Random();
    private static final ScheduledExecutorService SCHEDULER = Executors.newScheduledThreadPool(1);

    public static void scheduleRandomTask(int i) {
        // 生成随机延迟时间
        int delayInSeconds = RANDOM.nextInt(60);
        System.out.println("任务" + i + "将在 " + delayInSeconds + " 秒后执行");
        // 安排任务
        SCHEDULER.schedule(() -> {
            // 执行你的任务逻辑
            System.out.println("任务" + i + "开始执行");
            System.out.println("当前时间：" + LocalDateTime.now());
        }, delayInSeconds, TimeUnit.SECONDS);
    }
}
